﻿using System;
using System.Collections.Generic;
using Autodesk.Revit.DB;
using YArchitech.Revit;
using HYRevitCode.RevitDimensionUtility;

namespace HYOpeningCommon.ProvideData2TrackDim
{
	public class TrackDimData
	{
		public TrackDimData(Autodesk.Revit.DB.Document doc)
		{
			this.m_doc = doc;
		}

		public Line CreateDimLine(XYZ ve, XYZ vectorLine, XYZ ptRecent, XYZ ptProject, double dValue)
		{
			double num = 4.0;
			XYZ xyz = ptRecent + vectorLine * num + ve * num;
			XYZ xyz2 = ptProject + vectorLine * num + ve * (num + dValue);
			return Line.CreateBound(xyz, xyz2);
		}

		public bool DeleteDimLine(List<string> lstLineGuid)
		{
			if (lstLineGuid.Count == 0)
			{
				return true;
			}
			Transaction transaction = new Transaction(this.m_doc, "DeleteDimLine");
			bool result;
			try
			{
				transaction.Start();
				foreach (string text in lstLineGuid)
				{
					Element element = this.m_doc.GetElement(text);
					if (element != null)
					{
						this.m_doc.DeleteElement(element);
					}
				}
				transaction.Commit();
				result = true;
			}
			catch (Exception)
			{
				transaction.Commit();
				result = false;
			}
			return result;
		}

		public ReferenceArray GetReference(ref List<string> lstGUID, List<XYZ> lstPt, XYZ vectorLine)
		{
			ReferenceArray referenceArray = new ReferenceArray();
			double num = 0.0032808398950131233;
			foreach (XYZ xyz in lstPt)
			{
				XYZ ptEnd = xyz + vectorLine * num;
				DetailCurve detailCurve = this.CreateDetailCurve(xyz, ptEnd);
				if (detailCurve == null)
				{
					lstGUID.Clear();
					return null;
				}
				Reference reference = new Reference(detailCurve);
				referenceArray.Append(reference);
				lstGUID.Add(detailCurve.UniqueId);
			}
			return referenceArray;
		}

		private DetailCurve CreateDetailCurve(XYZ ptStart, XYZ ptEnd)
		{
			Transaction transaction = new Transaction(this.m_doc, "CreateDetailCurve");
			DetailCurve result;
			try
			{
				transaction.Start();
				Line line = Line.CreateBound(ptStart, ptEnd);
				DetailCurve detailCurve = this.m_doc.Create.NewDetailCurve(this.m_doc.ActiveView, line);
				transaction.Commit();
				result = detailCurve;
			}
			catch (Exception)
			{
				result = null;
			}
			return result;
		}

		public void CreateDim(List<DimData> lstDimData)
		{
			new FilteredElementCollector(this.m_doc).OfClass(typeof(DimensionType)).WhereElementIsElementType().ToElements();
			DimensionType dimensionType = null;
			Transaction transaction = new Transaction(this.m_doc, "HYScaleDimension");
			try
			{
				transaction.Start();
				dimensionType = RevitDimensionUtiltyMethod.GetDimensionType(this.m_doc, DimensionTypeEnum.ScaleDimension, null);
				transaction.Commit();
			}
			catch (Exception)
			{
			}
			if (dimensionType == null)
			{
				return;
			}
			foreach (DimData dimData in lstDimData)
			{
				dimData.CreateDim(this.m_doc, dimensionType);
			}
		}

		private Document m_doc;
	}
}
